package com.lbj.mvvm.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.lbj.mvvm.helper.getVMClazz

abstract class JetpackVMDBActivity<VM : JetpackVM, DB : ViewDataBinding> : AppCompatActivity() {
    lateinit var VM: VM
    lateinit var binding: DB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        createViewDataBinding()
        VM = createViewModel()
        registerDefUIChange()
        initStart()
    }

    abstract fun layoutId(): Int
    abstract fun initStart()
    abstract fun showLoading(message: String = "请稍后...")
    abstract fun dismissLoading()

    /**
     * 创建DataBinding
     */
    private fun createViewDataBinding() {
        binding = DataBindingUtil.setContentView(this, layoutId())
        binding.lifecycleOwner = this
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVMClazz(this) as Class<VM>)
    }

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        VM.defUI.showDialog.observe(this, Observer {
            showLoading(
                if (it.isEmpty()) {
                    "请求网络中..."
                } else it
            )
        })
        VM.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })
    }
}